package com.sdy.supermarket.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.supermarket.biz.mapper.GsHomeManageMapper;
import com.sdy.supermarket.biz.model.GsCooperationUnit;
import com.sdy.supermarket.biz.mapper.GsCooperationUnitMapper;
import com.sdy.supermarket.biz.model.GsHomeManage;
import com.sdy.supermarket.biz.service.GsCooperationUnitService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.supermarket.biz.vo.CoopVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hyh
 * @since 2019-08-05
 */
@Slf4j
@Service
public class GsCooperationUnitServiceImpl extends BaseServiceImpl<GsCooperationUnit> implements GsCooperationUnitService {
    @Resource
    private GsCooperationUnitMapper gsCooperationUnitMapper;
    @Resource
    private GsHomeManageMapper gsHomeManageMapper;
    @Autowired
    private FsApi fsApi;

    @Override
    public IPage<GsCooperationUnit> pageList(Page<GsCooperationUnit> page, String cooName) {
        LambdaQueryWrapper<GsCooperationUnit> lambda = new LambdaQueryWrapper<>();
        lambda.orderByAsc(GsCooperationUnit::getSort);
        if (StringUtil.isNotEmpty(cooName) && StringUtil.isNotBlank(cooName)) {
            lambda.like(GsCooperationUnit::getCooperationUnit, cooName);
        }
        IPage<GsCooperationUnit> iPage = page(page, lambda);
        List<String> fileId = iPage.getRecords().stream().map(GsCooperationUnit::getLogoImgUrl).collect(Collectors.toList());
        List<FileObj> fileListInfo = fsApi.getFileListInfo(fileId);
        for (FileObj file : fileListInfo) {
            for (GsCooperationUnit coo : iPage.getRecords()) {
                if (coo.getLogoImgUrl() != null && coo.getLogoImgUrl().equals(file.getId())) {
                    coo.setLogoImgUrl(file.getPath());
                }
            }
        }
        return iPage;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int deleteById(Integer id) throws BizException {
        Assert.isNull(id, "ID为NULL");
        GsCooperationUnit gsCooperationUnit = gsCooperationUnitMapper.selectById(id);
        Assert.isNull(gsCooperationUnit, "目标为空");
        LambdaQueryWrapper<GsCooperationUnit> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.gt(GsCooperationUnit::getSort, gsCooperationUnit.getSort());
        List<GsCooperationUnit> unitList = gsCooperationUnitMapper.selectList(lambdaQuery);
        unitList.forEach(coo -> coo.setSort(coo.getSort() - 1));
        int batchUpdateStatus = 1;
        if (!unitList.isEmpty()) {
            batchUpdateStatus = gsCooperationUnitMapper.batchUpdate(unitList);
        }
        int deleteStatus = gsCooperationUnitMapper.deleteById(id);
        int homeUpdate = gsHomeManageMapper.updateById(new GsHomeManage().setId(4).setLastUpdateTime(new Date()));
        if (batchUpdateStatus == 0 || deleteStatus == 0 || homeUpdate == 0) {
            throw new BizException("删除失败");
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int sortUpOrDown(Integer id, Integer type) throws BizException {
        Assert.isNull(id, "ID为NULL");
        Assert.isNull(type, "TYPE为NULL");
        GsCooperationUnit cooperationUnit = gsCooperationUnitMapper.selectById(id);
        Assert.isNull(cooperationUnit, "找不到目标对象");
        LambdaQueryWrapper<GsCooperationUnit> queryWrapper = new LambdaQueryWrapper<>();
        if (type == 0) {
            queryWrapper.orderByDesc(GsCooperationUnit::getSort).lt(GsCooperationUnit::getSort, cooperationUnit.getSort());
        }
        if (type == 1) {
            queryWrapper.orderByAsc(GsCooperationUnit::getSort).gt(GsCooperationUnit::getSort, cooperationUnit.getSort());
        }
        List<GsCooperationUnit> unitList = gsCooperationUnitMapper.selectList(queryWrapper);
        Assert.isNull(unitList.size() == 0, "当前排序已经达到最高或最低");
        // 主动变更排序的对象
        GsCooperationUnit unitUp = new GsCooperationUnit();
        unitUp.setId(id);
        unitUp.setSort(unitList.get(0).getSort());
        // 被动变更排序的对象
        GsCooperationUnit unitDown = new GsCooperationUnit();
        unitDown.setId(unitList.get(0).getId());
        unitDown.setSort(cooperationUnit.getSort());
        int unitUpStatus = gsCooperationUnitMapper.updateById(unitUp);
        int unitDownStatus = gsCooperationUnitMapper.updateById(unitDown);
        int homeUpdate = gsHomeManageMapper.updateById(new GsHomeManage().setId(4).setLastUpdateTime(new Date()));
        if (unitDownStatus == 0 || unitUpStatus == 0 || homeUpdate == 0) {
            throw new BizException("修改失败");
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int saveOrUpdateCoo(GsCooperationUnit cooperationUnit) throws BizException {
        List<GsCooperationUnit> list = gsCooperationUnitMapper.selectList(new LambdaQueryWrapper<>());
        if (cooperationUnit.getId() == null) {
            cooperationUnit.setSort(list.size() + 1);
            cooperationUnit.setCreateTime(new Date());
        }
        if (cooperationUnit.getId() != null) {
            cooperationUnit.setSort(null);
            cooperationUnit.setCreateTime(null);
        }
        boolean saveOrUpdate = saveOrUpdate(cooperationUnit);
        int homeUpdate = gsHomeManageMapper.updateById(new GsHomeManage().setId(4).setLastUpdateTime(new Date()));
        Assert.isTrue(!saveOrUpdate || homeUpdate == 0, "操作失败");
        return saveOrUpdate ? 1 : 0;
    }

    @Override
    public List<CoopVO> listValidCoop() {
        List<GsCooperationUnit> list = lambdaQuery()
                .eq(GsCooperationUnit::getDisplayStatus, 0)
                .orderByAsc(GsCooperationUnit::getSort)
                .orderByDesc(GsCooperationUnit::getId)
                .last(" limit 0,6")
                .list();
        List<FileObj> fileListInfo = fsApi.getFileListInfo(list.stream().map(GsCooperationUnit::getLogoImgUrl).collect(Collectors.toList()));
        for (FileObj file : fileListInfo) {
            for (GsCooperationUnit ls : list) {
                if (ls.getLogoImgUrl().equals(file.getId())) {
                    ls.setFileInfo(file);
                }
            }
        }
        return JsonUtil.convertCollection(list, List.class, CoopVO.class);
    }
}
